using System.Collections;

namespace ParboiledSharp
{
    public class ValueStack
    {
        private ArrayList _values;
        internal ValueStack()
        {
            _values = new ArrayList(50);
        }

        public object Pop()
        {
            object value = _values[_values.Count - 1];
            _values.RemoveAt(_values.Count - 1);
            return value;
        }

        public object Pop(int pos)
        {
            object value = _values[_values.Count - 1-pos];
            _values.RemoveAt(_values.Count - 1-pos);
            return value;
        }

        /// <summary>
        /// Search string in stack with specified prefix
        /// </summary>
        public string PopStringWithThePrefix(string prefix)
        {
            for (int i = _values.Count - 1; i >= 0; i--) {
                object value = _values[i];
                if (!(value is string)) continue;
                string str = (string)value;
                if (str.StartsWith(prefix)) {
                    _values.RemoveAt(i);
                    return str.Substring(prefix.Length);
                }
            }

            return null;
        }

        public int Count()
        {
            return _values.Count;
        }

        public object Peek()
        {
            return _values[_values.Count - 1];
        }

        public object Peek(int index)
        {
            return _values[_values.Count - 1-index];
        }

        public object Push(object value)
        {
            _values.Add(value);
            return value;
        }

        public ValueStack Clone()
        {
            ValueStack stack = new ValueStack();
            ArrayList newValues = new ArrayList(_values.Count + 10);
            newValues.InsertRange(0, _values);
            stack._values = newValues;
            return stack;
        }
    }
}
